package at.jku.se.fastsell.db4o.transactions;

import at.jku.se.fastsell.data.Auction;
import at.jku.se.fastsell.data.Bid;
import at.jku.se.fastsell.db4o.DatabaseException;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class StoreAuctionTransaction extends Transaction<Void> {
	
	private Auction a;
	
	// --------------------------------------------------------------------------------------------
	
	public StoreAuctionTransaction(Auction a) {
		this.a = a;
	}
	
	// --------------------------------------------------------------------------------------------

	@Override
	public Void run() throws DatabaseException {
//	    Key key = KeyFactory.createKey("Auction", "Fastsell");
	    
	    Entity auctionEntity = new Entity("Auction", key);
	    auctionEntity.setProperty("title", a.getTitle());
	    auctionEntity.setProperty("price", a.getCurPrice());
//	    auctionEntity.setProperty("active", a.isActive());
	    auctionEntity.setProperty("end", a.getEnd());
//	    auctionEntity.setProperty("remaining", a.getRemainingTime());
	    auctionEntity.setProperty("id", a.getAuctionID());
	    auctionEntity.setProperty("description", a.getDescription());
	    auctionEntity.setProperty("bidCount", a.getBidCount());
	    auctionEntity.setProperty("start", a.getStart());

	    for (Bid b : a.getBids()) {
	    	StoreBidTransaction bidTransaction = new StoreBidTransaction(b);
	    	bidTransaction.run();
	    }
	    
	    
	    StoreUserTransaction userTransaction = new StoreUserTransaction(a.getSeller());
	    userTransaction.run();
	    auctionEntity.setProperty("seller", a.getSeller().getName());
	    
	    
//	    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    datastore.put(auctionEntity);
	    return null;
	    
	}
	
	// --------------------------------------------------------------------------------------------
	
	@Override
	public String toString() {
		return super.toString() + ": " + a;
	}

}
